import { Component } from 'react';
import { findDOMNode } from 'react-dom';
import { os } from 'wpt';

function stopScrollBubble(dom = document.body) {
    let start = 0;
    let scrollTop;
    let scrollHeight;
    let clientHeight;

    const touchstart = e => {
        start = e.touches[0].clientY;
        scrollTop = dom.scrollTop;
        scrollHeight = dom.scrollHeight;
        clientHeight = dom.clientHeight;
    };
    const touchmove = e => {
        const move = e.touches[0].clientY;

        if ((move - start > 0 && scrollTop == 0) || (move - start < 0 && scrollTop == scrollHeight - clientHeight)) {
            e.preventDefault();
        }
    };

    dom.addEventListener('touchstart', touchstart);
    dom.addEventListener('touchmove', touchmove);

    return () => {
        dom.removeEventListener('touchstart', touchstart);
        dom.removeEventListener('touchmove', touchmove);
    };
}

export default class ScrollFixer extends Component {
    static defaultProps = {
        // 可滚动节点
        scrollBox: '',
    }

    componentDidMount() {
        if (!os.PC) {
            // eslint-disable-next-line react/no-find-dom-node
            const dom = findDOMNode(this);
            const scrollDom = this.props.scrollBox && dom.querySelector(this.props.scrollBox) || dom;

            this.removeListener = stopScrollBubble(scrollDom);
        }
    }

    componentWillUnmount() {
        this.removeListener && this.removeListener();
    }

    render() {
        return this.props.children;
    }
}
